package com.dream.base.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

import com.dream.app.cache.AppCodeCache;
import com.dream.app.cache.AppGroupCache;
import com.dream.app.cache.AppOrgCache;
import com.dream.app.cache.AppPositionCache;
import com.dream.base.web.job.InitialDatabaseService;
import com.dream.model.app.AppAbstractUser;
import com.dream.utils.date.DateParseUtils;
import com.dream.vo.base.Constants;
import com.dream.vo.base.MvcValidtorResult;
import com.google.common.collect.Maps;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013/8/29
 */

public abstract class BaseController {
	
	protected static final String RESULT_TYPE="type";
	protected static final String RESULT_CONTENT="content";
	
	protected static final Map<String,HttpSession> ACTIVE_SESSION = Maps.newConcurrentMap();
	
	@Autowired
	protected AppGroupCache appGroupCache;
	
	@Autowired
	protected LocaleResolver localeResolver;
	
	@Autowired
	protected AppPositionCache appPositionCache;
	
	@Autowired
	protected MessageSource messageSource;
	
	@Autowired
	protected AppOrgCache appOrgCache;
	
	@Autowired
	protected AppCodeCache appCodeCache;
	
	@Autowired
	private InitialDatabaseService initialDatabaseService;

	
	@ModelAttribute("userMe")
	public AppAbstractUser getUser(){
		
		HttpServletRequest httpRequest =  getRequest();
		HttpSession session = httpRequest.getSession(false);
		AppAbstractUser user = null;
		if(session != null){
			user = (AppAbstractUser)session.getAttribute(Constants.USER_ID);
		}
		
		return user;
	}
	
	public HttpServletRequest getRequest(){
		
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	public String getLoginUri(){
		
		return getRequest().getContextPath() + Constants.APP_LOGIN;
	}
	
	public Locale getLocale(){
		
		return localeResolver.resolveLocale(getRequest());
	}
	
	@ModelAttribute("root")
	public String getWebRoot(){
		return getRequest().getContextPath() + Constants.APP_PREFIX;
	}
	
	@ModelAttribute("now")
	public Date getCurrentDate(){
		return new Date();
	}
	
	@ModelAttribute("today")
	public String today(){
		return DateParseUtils.format(new Date());
	}
	
	/*** validation tools start ***/
	public  MvcValidtorResult populateErrors(BindingResult result){
		
		MvcValidtorResult myResult = new MvcValidtorResult();
		if(result.hasFieldErrors()){
			for(FieldError item : result.getFieldErrors()){
				
				String[] arguments = getArguments(item.getDefaultMessage());
				String[] args = null;
				if(ArrayUtils.isNotEmpty(arguments) || arguments.length > 1){
					args = Arrays.copyOfRange(arguments, 1, arguments.length);
				}
				addFieldMessage(myResult,item.getField(),arguments[0],args);
			}
		}
		
		if(result.hasGlobalErrors()){
			for(FieldError item : result.getFieldErrors()){
				
				String[] arguments = getArguments(item.getDefaultMessage());
				String[] args = null;
				if(ArrayUtils.isNotEmpty(arguments) || arguments.length > 1){
					args = Arrays.copyOfRange(arguments, 1, arguments.length);
				}
				addGlobalMessage(myResult,arguments[0],args);
			}
		}
		return myResult;
		
	}
	
	private String[]  getArguments(String message){
		
		String[] msg = new String[]{message};;
		if(message.contains(",")){
			msg = message.split(",");
		}
		
		return msg;
		
	}
	
	public   void addFieldMessage(MvcValidtorResult result,String id,String code){
		
		addFieldMessage(result,id,code,null);
	}
	
	public  void addFieldMessage(MvcValidtorResult result,String id,String code,Object[] arguments){
		if(result == null){
			return;
		}
		String error = messageSource.getMessage(code, arguments,this.getLocale());
		result.getFieldErrors().put(id, error);
	}
	
	public   void addGlobalMessage(MvcValidtorResult result,String code){
		
		addGlobalMessage(result,code,null);
	}
	
	public  void addGlobalMessage(MvcValidtorResult result,String code,Object[] arguments){
		if(result == null){
			return;
		}
		String error = messageSource.getMessage(code, arguments,this.getLocale());
		result.getGlobalErrors().add(error);
	}
    /*** validation tools end ***/
	
}
